package com.mybatis.data;

import com.mybatis.beans.SCData;
import com.mybatis.mapper.SCDataMapper;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.*;
import java.text.ParseException;
import java.util.Date;

/**
 * Created by James on 2017/4/4.
 * From 咕泡学院出品
 * 老师咨询 QQ 2904270631
 */
public class DataReader {

    private static SqlSession sqlSession = null;

    public static void read(String csvFile) throws IOException, ParseException {
        BufferedReader reader = new BufferedReader(new FileReader(new File(csvFile)));
        String line = null;
        int i = 0;
        while (null != (line = reader.readLine()) && i < 19000) {
            if (i == 0) {
                i++;
                continue;
            }
             SCData data = mappingToBean(line);
            SCDataMapper mapper = getSqlSession().getMapper(SCDataMapper.class);
            try {
                mapper.insert(data);
            } catch (Exception e) {
                System.out.println("错误 " + line);
            }
            System.out.println("完成 "+i);
            i++;
        }
    }

    private static SCData mappingToBean(String line) {
        String[] contents = line.split(",");
        SCData data = new SCData();
        data.setUserName(contents[1]);
        try {
            data.setBirthday(DateUtils.parseDate(contents[5], "yyyy-MM-dd"));
            data.setSchoolStartTime(DateUtils.parseDate(contents[9], "yyyy-MM"));
        } catch (ParseException e) {
            System.out.println("错误 " + line);
        }
        data.setSchool(contents[7]);
        data.setMobile(contents[13]);
        data.setCreatedTime(new Date());
        return data;
    }

    public static SqlSession getSqlSession() throws FileNotFoundException {
        InputStream configFile = new FileInputStream("E:\\workspace\\code\\mybatis-archetype\\src\\main\\java\\com\\gupaoedu\\mybatis\\data\\mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configFile);
        if (null == sqlSession) {
            sqlSession = sqlSessionFactory.openSession();
        }
        return sqlSession;
    }

    public static void main(String[] args) throws IOException, ParseException {
        try {
            read("E:\\data\\sichuang.csv");
        } finally {
            sqlSession.commit();
            sqlSession.close();
        }
    }
}
